/* eslint-disable no-unused-vars */
// 压缩前将file转换成img对象
export function readImg(file) {
    return new Promise((resolve, reject) => {
     const img = new Image()
     const reader = new FileReader()
     reader.onload = function(e) {
      img.src = e.target.result
     }
     reader.onerror = function(e) {
      reject(e)
     }
     reader.readAsDataURL(file)
     img.onload = function() {
      resolve(img)
     }
     img.onerror = function(e) {
      reject(e)
     }
    })
   }
   /**
    * 压缩图片
    *@param img 被压缩的img对象
    * @param type 压缩后转换的文件类型
    * @param mx 触发压缩的图片最大宽度限制
    * @param mh 触发压缩的图片最大高度限制
    */
   export function compressImg(img, type, mx, mh) {
       console.log('压缩图片')
    return new Promise((resolve, reject) => {
     const canvas = document.createElement('canvas')
     const context = canvas.getContext('2d')
     const { width: originWidth, height: originHeight } = img
     // 最大尺寸限制
     const maxWidth = mx
     const maxHeight = mh
     // 目标尺寸
     let targetWidth = originWidth
     let targetHeight = originHeight
     if (originWidth > maxWidth || originHeight > maxHeight) {
      if (originWidth / originHeight > 1) {
       // 宽图片
       targetWidth = maxWidth
       targetHeight = Math.round(maxWidth * (originHeight / originWidth))
      } else {
       // 高图片
       targetHeight = maxHeight
       targetWidth = Math.round(maxHeight * (originWidth / originHeight))
      }
     }
     canvas.width = targetWidth
     canvas.height = targetHeight
     context.clearRect(0, 0, targetWidth, targetHeight)
     // 图片绘制
     context.drawImage(img, 0, 0, targetWidth, targetHeight)
     canvas.toBlob(function(blob) {
      resolve(blob)
     }, type || 'image/png') })
   }

   export function clearHTML(data){
    let reg = /<[^>]+>/g;
    if(reg.test(data))
        return data.replace(/<.*?>/ig,"")
    else
       return data;
   }

   export function getHeadPicUrl(data){
        if(data){
            let status1 = data.search('<headpicsplit>')
            let status2 = data.search('<img>')
            if(status1!=-1)
            {
                let result = data.split('<headpicsplit>')[0]
                return result;
            }
            else{
                if(status2!=-1){
                    let temp = data.split('src=')[1]
                    let result = temp.split(">")[0]
                    return result
                }
            }
        }
        else
            return ''
    }

    export function handleTopics(posts,likes,collections){

        console.log('开始处理帖子信息-----------')


        posts.forEach(post => {
            if(likes!=''){
                likes.forEach(like =>{
                    if(like == post.postNo)
                        post.likeStatus = true;
                })
            }

            if(collections!=''){
                collections.forEach(collection=>{
                    if(collection == post.postNo)
                        post.collectStatus = true;
                })
            }
            
        });
        console.log("处理完成后的posts",posts)
        return posts;

    }//为帖子增加点赞信息

    export function handleComments(comments,likes,collections){
        
        console.log('开始处理评论信息-----------')


        comments.forEach(comment => {
            if(likes!=''){
                likes.forEach(like =>{
                    if(like == comment.commentNo)
                        comment.likeStatus = true;
                })
            }
            if(collections!=''){
                collections.forEach(collection=>{
                    if(collection == comment.commentNo)
                        comment.collectStatus = true;
                })
            }
            
        });
        console.log("处理完成后的评论",comments)
        return comments;
    }



    //输入框高度自适应

    let hiddenTextarea;

    const HIDDEN_STYLE = `
    height:0 !important;
    visibility:hidden !important;
    overflow:hidden !important;
    position:absolute !important;
    z-index:-1000 !important;
    top:0 !important;
    right:0 !important
    `;

    const CONTEXT_STYLE = [
    'letter-spacing',
    'line-height',
    'padding-top',
    'padding-bottom',
    'font-family',
    'font-weight',
    'font-size',
    'text-rendering',
    'text-transform',
    'width',
    'text-indent',
    'padding-left',
    'padding-right',
    'border-width',
    'box-sizing'
    ];

    function calculateNodeStyling(targetElement) {
    const style = window.getComputedStyle(targetElement);

    const boxSizing = style.getPropertyValue('box-sizing');

    const paddingSize = (
        parseFloat(style.getPropertyValue('padding-bottom')) +
        parseFloat(style.getPropertyValue('padding-top'))
    );

    const borderSize = (
        parseFloat(style.getPropertyValue('border-bottom-width')) +
        parseFloat(style.getPropertyValue('border-top-width'))
    );

    const contextStyle = CONTEXT_STYLE
        .map(name => `${name}:${style.getPropertyValue(name)}`)
        .join(';');

    return { contextStyle, paddingSize, borderSize, boxSizing };
    }

    export function calcTextareaHeight(
    targetElement,
    minRows = 1,
    maxRows = null
    ) {
    if (!hiddenTextarea) {
        hiddenTextarea = document.createElement('textarea');
        document.body.appendChild(hiddenTextarea);
    }

    let {
        paddingSize,
        borderSize,
        boxSizing,
        contextStyle
    } = calculateNodeStyling(targetElement);

    hiddenTextarea.setAttribute('style', `${contextStyle};${HIDDEN_STYLE}`);
    hiddenTextarea.value = targetElement.value || targetElement.placeholder || '';

    let height = hiddenTextarea.scrollHeight;
    const result = {};

    if (boxSizing === 'border-box') {
        height = height + borderSize;
    } else if (boxSizing === 'content-box') {
        height = height - paddingSize;
    }

    hiddenTextarea.value = '';
    let singleRowHeight = hiddenTextarea.scrollHeight - paddingSize;

    if (minRows !== null) {
        let minHeight = singleRowHeight * minRows;
        if (boxSizing === 'border-box') {
        minHeight = minHeight + paddingSize + borderSize;
        }
        height = Math.max(minHeight, height);
        result.minHeight = `${ minHeight }px`;
    }
    if (maxRows !== null) {
        let maxHeight = singleRowHeight * maxRows;
        if (boxSizing === 'border-box') {
        maxHeight = maxHeight + paddingSize + borderSize;
        }
        height = Math.min(maxHeight, height);
    }
    result.height = `${ height }px`;
    hiddenTextarea.parentNode && hiddenTextarea.parentNode.removeChild(hiddenTextarea);
    hiddenTextarea = null;
    return result;
    }
    //输入框高度自适应函数如上

    //处理初始topic数据，超出部分以省略号显示
    export function cutTopicContent(data){
        if(data.length>142)
            return data.substr(0,142) + '...' ;
        else
            return data;
    }

    //获取当前时间，24小时制
    export function getLocalTime(){
        let newdate = new Date();
        let time = newdate.toLocaleString('chinese',{ hour12: false })
        time = time.replace(/\//g,'-')
        return time;
    }
    
    //初始化处理评论
    export function intializeComments(comments,users,userdetails){
        console.log(comments,users)
       for(let i=0;i<comments.length;i++){
           comments[i].userinfo = users[i]
           comments[i].userinfo.nickname = userdetails[i].userNickname
       }
       return comments
    }

    //初始化标签选中状态
    export function addTagsStatus(tags,status){
        for(let i=0;i<tags.length;i++){
            tags[i].checked = status;
        }
        console.log("初始化标签:",tags)
        return tags
    }

    //清除通知信息无效数据
    export function removeUselessNoti(notifications){
        for(let i=0;i<notifications.length;i++){
            if(notifications[i].contextData==null || notifications[i].notificationType == 6){
                notifications.splice(i,1)
                i=0
            }
        }
        console.log('删除无效通知',notifications)
        return notifications
    }